﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Modles.Models;

namespace BilbilDAL
{
    public class UploadVideoDAL
    {
        /// <summary>
        /// 上传视频文件信息到数据库
        /// </summary>
        /// <param name="videoInfo">视频信息</param>
        /// <param name="videoAddress">视频文件存储路径</param>
        /// <param name="imageAddress">封面图片存储路径</param>
        /// <returns>视频信息ID</returns>
        public int AddVideoInfo(VideoInfo videoInfo, string videoAddress, string imageAddress)
        {
            try
            {
                using (VideoPlatformDbContext con = new VideoPlatformDbContext())
                {
                    using (var transaction = con.Database.BeginTransaction())
                    {
                        try
                        {
                            // 1. 添加视频文件信息
                            var video = new Video
                            {
                                Address = videoAddress,
                            };
                            con.Videos.Add(video);
                            con.SaveChanges();

                            // 2. 添加封面图片信息
                            var image = new Image
                            {
                                Address = imageAddress,
                                Description = videoInfo?.Title ?? "视频封面",
                            };
                            con.Images.Add(image);
                            con.SaveChanges();

                            // 3. 添加视频信息
                            videoInfo.VideoId = video.Id;
                            videoInfo.ImageId = image.Id;
                            videoInfo.Time = DateTime.Now;
                            videoInfo.Like = 0;
                            videoInfo.Views = 0;

                            con.VideoInfos.Add(videoInfo);
                            con.SaveChanges();

                            // 提交事务
                            transaction.Commit();

                            return videoInfo.Id;
                        }
                        catch
                        {
                            // 回滚事务
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }
            catch
            {
                return -1; // 返回-1表示失败
            }
        }
    }
}
